import flet as ft
from flet import (
    alignment,
    border_radius
)
import webbrowser

import PublicConstant


class PicUnit(ft.UserControl):
    def __init__(self, _pic_id: int, _like_num: int, _is_r18: bool):
        super(PicUnit, self).__init__()

        self.pic_id = _pic_id
        self.like_num = _like_num
        self.is_r18 = _is_r18

        self.img = ft.Image(
            src=f'{PublicConstant.thumbnail_path}{self.pic_id}.jpg',
            border_radius=border_radius.all(10)
        )

    def __lt__(self, other: int):
        return self.like_num > other

    def update_info(self, _pic_id: int, _is_r18: bool, _like_num: int):
        self.pic_id = _pic_id
        self.is_r18 = _is_r18
        self.like_num = _like_num
        self.update()

    def build(self):
        # asyncio.run(self.load_thumb())
        return ft.Stack(controls=[
            self.img,
            ft.Container(
                content=ft.ElevatedButton(
                    text='R-18' if self.is_r18 else 'Safe',
                    on_click=lambda _: webbrowser.open_new_tab(
                        f'https://www.pixiv.net/artworks/{self.pic_id}'
                    ),
                    color='#FFFFFF' if self.is_r18 else None,
                    bgcolor='#FF0000' if self.is_r18 else None
                ),
                alignment=alignment.bottom_left,
                padding=3
            )
        ])
